<template>
  <div class="task-detail-container" v-loading="pageLoading">
    <template v-if="showPage">
      <div class="task-detail-header common-detail-header">
        <div class="top-box">
          <!-- 订单状态 -->
          <OrderState :state="dataInfo.logisticsState" />
          <!-- 按钮组 -->
          <div class="order_button_group" v-if="editedPermission && dataInfo.refundState !=1">
            <el-button
              v-if="dataInfo.refundApproveBtn"
              type="primary"
              @click="approve(dataInfo)"
              >{{ $t('common.base.approve')}}</el-button
            >
            <template
              v-if="
                dataInfo.logisticsState === 1 ||
                dataInfo.logisticsState === 2 ||
                dataInfo.logisticsState === 3
              "
            >
              <el-button type="plain-third" @click="openDialog('edit')"
                >{{$t('order.detailV2.modifyOrder')}}</el-button
              >
            </template>
            <el-button
              type="plain-third"
              v-if="
                dataInfo.logisticsState === 1 || dataInfo.logisticsState === 2
              "
              @click="handleCancelOrder()"
              >{{$t('order.detailV2.cancelOrder')}}</el-button
            >
            <template
              v-if="
                (dataInfo.logisticsState === 2 || dataInfo.logisticsState === 3) && (dataInfo.refundState !== 0)
              "
            >
              <el-tooltip
                class="item"
                effect="dark"
                :content="$t('order.tips.tooltipText1')"
                placement="top"
                :disabled="!dataInfo.underApproval"
              >
                <div style="display: inline; margin-left: 12px">
                  <base-button
                    type="primary"
                    icon="icon-add1"
                    @event="openDialog('services')"
                    :disabled="dataInfo.underApproval"
                    >{{$t('task.setting.taskTypeSetting.manage.industryNames.name7')}}</base-button
                  >
                </div>
              </el-tooltip>
            </template>
            <template
              v-if="
                (dataInfo.logisticsState === 2 ||
                  dataInfo.logisticsState === 3) &&
                !isAllServices() && dataInfo.availableLogistics && (dataInfo.refundState !== 0)
              "
            >
              <el-tooltip
                class="item"
                effect="dark"
                :content="$t('order.tips.tooltipText2')"
                placement="top"
                :disabled="!dataInfo.underApproval"
              >
                <div style="display: inline; margin-left: 12px">
                  <base-button
                    type="primary"
                    icon="icon-add1"
                    @event="openDialog('deliver')"
                    :disabled="dataInfo.underApproval"
                    >{{$t('goods.component.expressDelivery')}}</base-button
                  >
                </div>
              </el-tooltip>
            </template>
            <!-- 新版额度结算按钮，暂时隐藏 -->
            <!-- <el-button
              style="margin-left: 12px"
              type="primary"
              @click="handleBalance"
              >{{ $t('common.base.settleAccounts') }}</el-button
            > -->
          </div>
          <div class="approving-img" v-if="dataInfo.refundApproveBtn">
            <img :src="approveImage" />
          </div>
        </div>
        <div class="order_info">
          <p>
            {{$t('order.detailV2.orderTime')}}：<span>{{ dataInfo.createTime | formatTime }}</span>
          </p>
          <p v-if="dataInfo.payTime">
            {{$t('order.detailV2.paymentTime')}}：<span>{{ dataInfo.payTime | formatTime }}</span>
          </p>
          <p v-if="dataInfo.firstLogisticsTime">
            {{$t('order.detailV2.deliveryTime')}}：<span>{{
              dataInfo.firstLogisticsTime | formatTime
            }}</span>
          </p>
        </div>
      </div>
      <div v-if="getLayout === 1" class="detail_h">
        <div class="detail">
           <!-- start 详情平铺布局 -->
          <BaseTileLayoutTabBar2
            :bar-list="mergeTabs"
            :now-item="currentTab.tabName"
            @changeItem="baseUpdate"
            @openLayoutModal="openBaseLayoutModal"
            class="layoutDialog2"
          ></BaseTileLayoutTabBar2>
          <!-- end 详情平铺布局 -->
          <div class="detail-layout">
            <el-tabs v-model="currentTab.tabName">
              <el-tab-pane :label="$t('event.detail.text3')" name="orderInfo">
                <OrderInfo :info="dataInfo" :form-cell-count="formCellCount"/>
              </el-tab-pane>
              <!-- 动态信息 -->
              <el-tab-pane
                :label="$t('common.base.dynamicInfo')"
                name="orderProgressRate"
                v-loading="orderProgressRateLoading"
              >
                <template v-if="currentTab.tabName == 'orderProgressRate'">
                  <div class="order_progress progress_column" v-if="!orderProgressRateLoading">
                    <!-- start 时间轴 -->
                    <template v-if="recordList.length">
                      <div class="base-timeline-wrap">
                        <base-timeline
                          :data="recordList"
                          :record-render="renderRecord"
                          :loading="recordLoading"
                          :loadmore="hasNextRecordPage"
                          @load="loadmore"
                        />
                      </div>
                      <div class="biz-comment-wrap">
                        <biz-comment
                          class="comment_bar"
                          ref="comment"
                          :placeholder="$t('common.base.tip.inputCommentContent')"
                          @submit="createRemark"
                          :disabled="recordLoading"
                          autofocus
                          user-search-url="/message/user/lists"
                          :search-params="{ seeAllOrg: true }"
                        ></biz-comment>
                      </div>
                    </template>
                    <template v-else>
                      <no-data-view :notice-msg="$t('common.base.noData')"></no-data-view>
                    </template>
                    <!-- end 时间轴 -->
                  </div>
                </template>
              </el-tab-pane>
              <!-- 商品信息 -->
              <el-tab-pane
                :label="$t('goods.detail.productInfo')"
                name="orderProductInfo"
                v-loading="orderProductInfoLoading"
              >
                <template v-if="currentTab.tabName == 'orderProductInfo'">
                  <order-products
                    class="card-info-container"
                    :list="orderCommodityList"
                    v-if="!orderProductInfoLoading"
                  />
                </template>
              </el-tab-pane>
              <!-- 物流信息 -->
              <el-tab-pane
                :label="$t('common.form.preview.sparepart.colum16')"
                name="orderLogisticsInfo"
                v-loading="orderLogisticsInfoLoading"
              >
                <template v-if="currentTab.tabName == 'orderLogisticsInfo'">
                  <logistics-view
                    class="card-info-container"
                    :list="logisticsInfoList"
                    :order-id="orderId"
                    ref="LogisticsDialogComponent"
                    v-if="!orderLogisticsInfoLoading"
                  />
                </template>
              </el-tab-pane>
              <!-- 关联服务 -->
              <el-tab-pane
                :label="$t('order.detailV2.associatedServices')"
                name="orderRelation"
                v-loading="orderRelationLoading"
              >
                <template v-if="currentTab.tabName == 'orderRelation'">
                  <relation-task
                    class="card-info-container"
                    :relation-task-list="myServiceList"
                    v-if="!orderRelationLoading"
                  />
                </template>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
      <!-- 商品详情折叠面板 -->
      <base-collapse
        class="task-detail-main-content detail-main-content"
        v-if="getLayout === 2"
        :show-collapse="true"
        :direction.sync="collapseDirection"
        style="position: relative;"
      >
        <template slot="left">
          <BaseTileLayoutTabBar2
            @openLayoutModal="openBaseLayoutModal"
            class="layoutDialog"
          ></BaseTileLayoutTabBar2>
          <div
            class="task-detail-main-content-left detail-main-content-left"
            v-show="collapseDirection != 'left'"
          >
            <el-tabs v-model="leftActiveTab">
              <el-tab-pane :label="$t('event.detail.text3')" name="orderInfo">
                <OrderInfo :info="dataInfo" />
              </el-tab-pane>
            </el-tabs>
          </div>
          <div class="collapse-left" v-show="collapseDirection == 'left'">
            {{ leftActiveTabText }}
          </div>
        </template>
        <!-- 动态信息 -->
        <template slot="right">
          <div
            class="task-detail-main-content-right detail-main-content-right"
            v-show="collapseDirection != 'right'"
          >
            <el-tabs
              v-model="rightActiveTab"
              ref="contactInfoTab"
              @tab-click="handleClick"
            >
              <!-- 动态信息 -->
              <el-tab-pane
                :label="$t('common.base.dynamicInfo')"
                name="orderProgressRate"
                v-loading="orderProgressRateLoading"
              >
                <template v-if="rightActiveTab == 'orderProgressRate'">
                  <div class="order_progress" v-if="!orderProgressRateLoading">
                    <!-- start 时间轴 -->
                    <template v-if="recordList.length">
                      <div class="base-timeline-wrap">
                        <base-timeline
                          :data="recordList"
                          :record-render="renderRecord"
                          :loading="recordLoading"
                          :loadmore="hasNextRecordPage"
                          @load="loadmore"
                        />
                      </div>
                      <div class="biz-comment-wrap">
                        <biz-comment
                          class="comment_bar"
                          ref="comment"
                          :placeholder="$t('common.base.tip.inputCommentContent')"
                          @submit="createRemark"
                          :disabled="recordLoading"
                          autofocus
                          user-search-url="/message/user/lists"
                          :search-params="{ seeAllOrg: true }"
                        ></biz-comment>
                      </div>
                    </template>
                    <template v-else>
                      <no-data-view :notice-msg="$t('common.base.noData')"></no-data-view>
                    </template>
                    <!-- end 时间轴 -->
                  </div>
                </template>
              </el-tab-pane>
              <!-- 商品信息 -->
              <el-tab-pane
                :label="$t('goods.detail.productInfo')"
                name="orderProductInfo"
                v-loading="orderProductInfoLoading"
              >
                <template v-if="rightActiveTab == 'orderProductInfo'">
                  <order-products
                    class="card-info-container"
                    :list="orderCommodityList"
                    v-if="!orderProductInfoLoading"
                  />
                </template>
              </el-tab-pane>
              <!-- 物流信息 -->
              <el-tab-pane
                :label="$t('common.form.preview.sparepart.colum16')"
                name="orderLogisticsInfo"
                v-loading="orderLogisticsInfoLoading"
              >
                <template v-if="rightActiveTab == 'orderLogisticsInfo'">
                  <logistics-view
                    class="card-info-container"
                    :list="logisticsInfoList"
                    :order-id="orderId"
                    ref="LogisticsDialogComponent"
                    v-if="!orderLogisticsInfoLoading"
                  />
                </template>
              </el-tab-pane>
              <!-- 关联服务 -->
              <el-tab-pane
                :label="$t('order.detailV2.associatedServices')"
                name="orderRelation"
                v-loading="orderRelationLoading"
              >
                <template v-if="rightActiveTab == 'orderRelation'">
                  <relation-task
                    class="card-info-container"
                    :relation-task-list="myServiceList"
                    v-if="!orderRelationLoading"
                  />
                </template>
              </el-tab-pane>
            </el-tabs>
          </div>

          <div class="collapse-right" v-show="collapseDirection == 'right'">
            {{ rightActiveTabText }}
          </div>
        </template>
      </base-collapse>
      <!-- 快递发货弹窗 -->
      <DeliverGoodsDialog ref="deliverGoodsRef" @reloadPage="getData" />
      <!-- 上门服务弹窗 -->
      <OnsiteServicesDialog ref="onsiteServicesRef" @reloadPage="getData" />
      <!-- 修改订单弹窗 -->
      <EditOrderDialog ref="editOrderRef" @reloadPage="getData" />
      <OrderApproveDialog ref="orderApproveDialog" @reloadPage="editOrder"/>
      <!-- 结算弹窗 -->
      <biz-form-dialog
        ref='BizFormDiaLogComponent'
        :button-text="$t('common.base.settleAccounts')"
        :title="$t('task.auditSettle')"
        :footer-tip="$t('order.detailV2.balanceTip')"
        :fields="balanceFields"
        :submit-function="handleBalanceSubmit"
      >
      </biz-form-dialog>
      <!-- 通栏弹窗 -->
      <biz-layout-modal
        ref="bizLayoutModal"
        :biz-layout-type="Layout"
        :columns="formCellCount"
        @changeLayout="changeDetailLayout">
      </biz-layout-modal>
    </template>
  </div>
</template>
<script>
import qs from '@src/util/querystring';
import moment from 'moment';
// API
import {
  orderDetails,
  orderDynamic,
  getSimpleLogistics,
  myService,
  orderWithCommodity,
  cancelOrder,
  addDynamic,
} from '@src/api/PortalApi';
/* components */
import OrderState from './component/orderState.vue';
import OrderInfo from './component/orderInfo.vue';
import OrderProducts from './component/orderProducts.vue';
import LogisticsView from './component/logisticsView.vue';
import RelationTask from './component/relationTask.vue';
import DeliverGoodsDialog from 'src/modules/linkc/order/component/DeliverGoodsDialog.vue';
import OnsiteServicesDialog from 'src/modules/linkc/order/component/OnsiteServicesDialog.vue';
import EditOrderDialog from 'src/modules/linkc/order/component/EditOrderDialog.vue';
import BaseTileLayoutTabBar2 from '@src/component/common/BaseTabBar/BaseTileLayoutTabBar2.vue';
import AuthMixin from '@src/mixins/authMixin';
import AuthUtil from '@src/util/auth';
import AuthEnum from '@model/enum/AuthEnum.ts';
import { isOpenData } from '@src/util/platform';
import { useTenantId } from '@hooks/useRootWindow.ts';
import NoDataView from '@src/component/common/NoDataViewNew';
import { t } from '@src/locales'
import { t as $t} from '@src/locales'
import { useStateSystemViewLayout } from 'pub-bbx-utils'
import { translateAction } from '@src/util/record'
import OrderApproveDialog from 'src/modules/linkc/order/component/OrderApproveDialog.vue';
import { getLocalesOssUrl } from '@src/util/assets'
const approveImage = getLocalesOssUrl('/task/approving.png')
import { getTaskBalanceFieldInfo } from '@src/api/TaskApi';

function createAttachmentDom(h, attachments) {
  return attachments && attachments.length > 0 ? (
    <div class="base-timeline-attachment base-file__preview">
      {attachments.map(item => (
        <base-file-item
          Source={attachments}
          file={item}
          key={item.id}
          readonly
          size="small"
        />
      ))}
    </div>
  ) : (
    ''
  );
}
function createLinkDom(h, s) {
  const reg =
    /((((https?|ftp?):(?:\/\/)?)(?:[-;:&=\+\$]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\?\+=&;:%!\/@.\w_]*)#?(?:[-\+=&;%!\?\/@.\w_]*))?)/g;
  const str = s.replace(reg, str => `@#@${str}@#@`);
  const arr = str.split('@#@');
  return (
    <p class="pre-line secondary-info">
      {arr.map(item => {
        if (item.indexOf('http') === 0) {
          return (
            <a href={item} target="_blank">
              {item}
            </a>
          );
        }
        return <biz-comment-html html={item}></biz-comment-html>;
      })}
    </p>
  );
}

export default {
  mixins: [AuthMixin],
  components: {
    OrderState,
    OrderInfo,
    OrderProducts,
    LogisticsView,
    RelationTask,
    DeliverGoodsDialog,
    OnsiteServicesDialog,
    EditOrderDialog,
    NoDataView,
    OrderApproveDialog,
    BaseTileLayoutTabBar2
  },
  provide: {
    initData: {},
  },
  data() {
    return {
      leftActiveTab: 'orderInfo',
      rightActiveTab: 'orderProgressRate',
      stateObj: {
        1: {
          name: this.$t('order.detailV2.toBeShipped'),
          key: 'unDeliveredCount',
        },
        2: {
          name: this.$t('order.detailV2.toBeReceived'),
          key: 'unReceivedCount',
        },
        3: {
          name: this.$t('common.base.usualStatus.finish'),
          key: 'completedCount',
        },
      },
      hasNextRecordPage: false,
      recordList: [],
      recordParams: {
        pageSize: 999,
        pageNum: 1,
      },
      recordLoading: false,
      searchData: {},
      dataInfo: {},
      logisticsInfoList: [],
      myServiceList: [],
      orderCommodityList: [],
      collapseDirection: '',
      showPage: false,
      pageLoading: false,
      orderProgressRateLoading: false,
      orderProductInfoLoading: false,
      orderLogisticsInfoLoading: false,
      orderRelationLoading: false,
      approveImage,
      balanceFields: [],
      Layout: 2,
      formCellCount: 1,
      tabPosition: '',
      currentTab: {
        tabName: ''
      }
    };
  },
  computed: {
    getLayout() {
      return this.Layout
    },
    leftBarList() {
      return [{
        tabName: this.leftActiveTab,
        disabled: true,
        tabShow: true,
        tabLabel: $t('event.detail.text3'),
        position: 'left'
      }]
    },
    rightBarList() {
      return [{
        tabName: 'orderProgressRate',
        disabled: true,
        tabShow: true,
        tabLabel: $t('common.base.dynamicInfo'),
        position: 'left'
      },{
        tabName: 'orderProductInfo',
        disabled: true,
        tabShow: true,
        tabLabel: $t('goods.detail.productInfo'),
        position: 'left'
      },{
        tabName: 'orderLogisticsInfo',
        disabled: true,
        tabShow: true,
        tabLabel: $t('common.form.preview.sparepart.colum16'),
        position: 'left'
      },{
        tabName: 'orderRelation',
        disabled: true,
        tabShow: true,
        tabLabel: $t('order.detailV2.associatedServices'),
        position: 'left'
      }]
    },
    mergeTabs() {
      return [...this.leftBarList, ...this.rightBarList]
    },
    orderId() {
      const queryObject = qs.parse(window.location.search);
      return queryObject.id ?? '';
    },
    isBalance() {
      const queryObject = qs.parse(window.location.search);
      return queryObject.isBalance ?? false;
    },
    // 编辑权限
    editedPermission() {
      return AuthUtil.hasAuth(
        this.globalLoginUserAuth,
        AuthEnum.SHIP_COMPLETE_ORDER
      );
    },
    leftActiveTabText() {
      let map = {
        orderInfo: this.$t('event.detail.text3'),
      };
      return map?.[this.leftActiveTab] ?? '';
    },
    rightActiveTabText() {
      let map = {
        orderProgressRate: this.$t('common.base.dynamicInfo'),
        orderProductInfo: this.$t('goods.detail.productInfo'),
        orderLogisticsInfo: this.$t('common.form.preview.sparepart.colum16'),
        orderRelation: this.$t('order.detailV2.associatedServices'),
      };
      return map?.[this.rightActiveTab] ?? '';
    },
  },
  filters: {
    formatTime(time) {
      if (!time) return;
      return moment(time).format('YYYY-MM-DD HH:mm:ss');
    },
  },
  async created() {
    try {
      this.pageLoading = true;
      let params = window.location.href.split('?')[1];
      let obj = {};
      if (params) {
        params.split('&').forEach(item => {
          let item_ = item.split('=');
          obj[item_[0]] = item_[1];
        });
      }
      this.searchData = obj;
      await this.getData();
      await this.initializeRecord();
    } finally {
      this.pageLoading = false;
      this.showPage = true;
    }
  },
  async mounted() {
    this.currentTab = {
      tabName: this.leftActiveTab
    }
    await this.initFormBuilderCellCount()
  },
  // async mounted() {
  //   await this.fetchBalanceFieldInfo();
  //   if (this.isBalance) this.handleBalance();
  // },
  methods: {
    async baseUpdate(item) {
      this.currentTab = item;
      this.handleClickColumn(this.currentTab)
    },
    openBaseLayoutModal() {
      this.$refs.bizLayoutModal.open()
    },
    changeDetailLayout(type, columns) {
      this.leftActiveTab = 'orderInfo' 
      this.Layout = type
      this.tabPosition = 'left'
      if(type === 2) {
        this.rightActiveTab = 'orderProgressRate' 
      }
      this.formCellCount = columns * 1
    },
    async initFormBuilderCellCount(){
      const { getSystemViewLayout } = useStateSystemViewLayout()
      const count = await getSystemViewLayout()
      this.Layout = count.baseLayout || 2;
      this.formCellCount = count.formCellCount || 1;
    },
    approve(item) {
      this.$refs.orderApproveDialog.openDialog(item.refundId)
      this.$refs.orderApproveDialog.visible = true
    },
    async getData() {
      this.pageLoading = true;
      await orderDetails({
        orderId: this.orderId,
      }).then(res => {
        if (res.code === '200') {
          this.dataInfo = res.data;

          if (this.dataInfo.orderNum) {
            const currentTabId = window.frameElement?.dataset?.id;
            this.$platform.setTabTitle({
              id: currentTabId,
              title: this.$t('common.pageTitle.pageOrderDetail', {orderNum: this.dataInfo.orderNum}),
            });
          }
        } else {
          this.$notify.close();
          this.$notify.error({
            title: this.$t('common.base.tip.httpIsError'),
            message: res.message,
            duration: 2000,
          });
        }
      }).finally(() => {
        this.pageLoading = false;
      });
    },
    // 修改订单请求数据
    editOrder() {
      this.getData();
      this.initializeRecord();
    },
    openDialog(action) {
      if (action === 'edit') {
        window.TDAPP.onEvent(this.$t('order.detailV2.orderManagement1'));
        let state = this.dataInfo.logisticsState;
        if (this.dataInfo.payType === 3 && this.dataInfo.logisticsState === 2)
          state = 1;
        const isShow = !this.isAllServices();
        this.$refs.editOrderRef.open(this.orderId, state, isShow);
      }

      if (action === 'deliver') {
        window.TDAPP.onEvent(this.$t('order.detailV2.orderManagement2'));
        this.$refs.deliverGoodsRef.open(this.orderId, this.dataInfo.firstDeliverGoods);
      }

      if (action === 'services') {
        window.TDAPP.onEvent(this.$t('order.detailV2.orderManagement3'));
        this.$refs.onsiteServicesRef.open(
          this.orderId,
          this.dataInfo.contactsPhone
        );
      }
    },
    handleClick(tab, event) {
      this.currentTab = {
        tabName: tab.name
      }
      if (tab.name === 'orderLogisticsInfo') {
        // 物流信息
        this.getLogisticsDetails();
      } else if (tab.name === 'orderRelation') {
        // 关联服务
        this.getMyService();
      } else if (tab.name === 'orderProductInfo') {
        // 关联服务
        this.getOrderCommodity();
      } else if (tab.name === 'orderProgressRate') {
        // 动态信息
        this.getOrderDynamic();
      }
    },
    /**
     * 多列改造中的点击
     */
    handleClickColumn(tab, event) {
      if (tab.tabName === 'orderLogisticsInfo') {
        // 物流信息
        this.getLogisticsDetails();
      } else if (tab.tabName === 'orderRelation') {
        // 关联服务
        this.getMyService();
      } else if (tab.tabName === 'orderProductInfo') {
        // 关联服务
        this.getOrderCommodity();
      } else if (tab.tabName === 'orderProgressRate') {
        // 动态信息
        this.getOrderDynamic();
      }
    },
    // 取消订单
    async handleCancelOrder() {
      try {
        if (!(await this.$platform.confirm('确定要取消选择的订单？'))) return;
        const { code, data } = await cancelOrder({
          orderId: this.orderId,
        });

        if (code !== '200' || !data) {
          return this.$message.error(this.$t('order.tips.cancelFailed'));
        }

        this.$message.success(this.$t('order.tips.cancelSuccess'));
        setTimeout(() => {
          this.getData();
        }, 1000);
      } catch (error) {
        console.error('handleGetParcelList error', error);
      }
    },
    // 获取动态信息
    async getOrderDynamic() {
      this.recordParams.orderId = this.orderId;
      this.orderProgressRateLoading = true;
      try {
        const res = await orderDynamic(this.recordParams);
        if (res.code === '200') {
          this.recordList = res.data.list || [];
        }
      } finally {
        this.orderProgressRateLoading = false;
      }
    },
    // 更多日志
    async loadmore() {
      try {
        this.recordParams.pageNum++;
        this.recordLoading = true;

        let result = await this.getOrderDynamic(this.recordParams);

        this.recordLoading = false;
        this.recordPage.merge(result);
      } catch (error) {
        console.warn('loadmore -> error', error);
      }
    },
    /** 根据记录的action渲染对应的内容，支持jsx和render函数 */
    renderRecord(h, item) {
      let {
        action,
        userName,
        showInOwn,
        content,
        attachments,
        staffId,
        userId,
      } = item;

      if (action == '备注') {
        return [
          <h5 class="main-info">
            <i18n path="common.record.task.somebodyAddRemark" class="main-info" tag="span">
              <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
            </i18n>
            {!!showInOwn && (
              <span class="private">
                <i class="iconfont icon-account1"></i>{t('common.record.onlyVisibleToYourself')}
              </span>
            )}
            。
            {
              // 暂时没有删除功能
              // this.allowDeleteRecord(item)
              // && <plink-button class="btn-text base-timeline-delete" onClick={e => this.deleteRemark(item)}>
              //     <i class="iconfont icon-shanchu"></i>删除
              // </plink-button>
            }
          </h5>,
          content.isDelete == 'true' ? (
            <i18n path="common.record.task.somebodyDeleteRemark" class="text-danger" tag="p">
              <span place="operator">
                {content.deleteUserName}
              </span>
              <span place="time">{content.deleteTime}</span>
            </i18n>
          ) : (
            [
              createLinkDom(h, content.updateContent),
              createAttachmentDom(h, attachments),
            ]
          ),
        ];
      } else if (action == '快递发货') {
        return [
          <h5 class="main-info">
            <i18n path="common.record.linkcOrder.send">
              <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
            </i18n>
            {content.logisticsInfo}
          </h5>,
        ];
      } else if (action == '支付') {
        return [
          <i18n path="common.record.linkcOrder.pay" class="main-info" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
          </i18n>,
          <p class="secondary-info">{t('common.form.preview.pay.payMethod')}：{content.payType}</p>,
        ];
      } else if (action == '上门服务') {
        return [
          <i18n path="common.record.linkcOrder.createService" class="main-info" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
            <span place="taskNo">{content.taskNo}</span>
          </i18n>,
        ];
      } else if (action == '修改物流' || action == '修改工单') {
        return [
          <i18n path={`common.record.linkcOrder.edit.${action == '修改物流' ? 'logistics' : 'task'}`} class="main-info" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
            <span place="value1">{content.oldService}</span>
            <span place="value2">{content.newService}</span>
          </i18n>,
        ];
      } else if (action == '修改订单') {
        return [
          <i18n path="common.record.linkcOrder.edit.order" class="main-info" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
          </i18n>,
          <p class="secondary-info">{t('common.base.modifyField')}：{content.editField}</p>,
        ];
      } else if (action == '拒绝出库') {
        return [
          <i18n path="common.record.linkcOrder.refuseOut" class="main-info" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
          </i18n>,
          <p class="secondary-info">{t('task.cancelReason')}：{content.fail}</p>,
        ];
      } else if (action == '出库失败') {
        return [
          <i18n path="common.record.linkcOrder.createOutFail" class="main-info" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
          </i18n>,
          <p class="secondary-info">{t('common.record.linkcOrder.failCause')}：{content.fail}</p>,
        ];
      } else if (action == '自动取消') {
        return [<h5 class="main-info">{t('common.record.linkcOrder.timeoutCancel')}</h5>];
      } else if (action == 'b端查询物流') {
        return [
          <h5 class="main-info">
            {this.renderUserName(userName, staffId, userId)} {t('common.record.linkcOrder.checkLogistics')}：{ content.logisticsLogStr }
          </h5>,
        ];
      } else if (action == 'c端查询物流') {
        return [
          <h5 class="main-info">
            {t('common.base.customer')} {this.renderUserName(userName, staffId, userId)} {t('common.record.linkcOrder.checkLogistics')}{ content.logisticsLogStr }
          </h5>,
        ];
      }else if (action == '自动完成') {
        return [
          <h5 class="main-info">
            {t('common.record.linkcOrder.orderAtuoFinished')}
          </h5>,
        ];
      }else if (action == '新建退款申请') {
        return [
          <i18n path="common.record.linkcOrder.createRefund" class="main-info" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
          </i18n>,
          <p class="secondary-info">{t('common.record.linkcOrder.refundMoney')}：{content.refundMoney}</p>,
          <p class="secondary-info">{t('common.record.linkcOrder.refundCause')}：{content.refundCause}</p>,
          createAttachmentDom(h, attachments),
        ];
      }else if (action == '退款审批') {
        return [
          <i18n path="common.record.linkcOrder.refundApprove" class="main-info" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
          </i18n>,
          <p class="secondary-info">{t('common.record.linkcOrder.refundResult')}：{content.refundApproveResult}</p>,
          <p class="secondary-info">{t('common.record.linkcOrder.refundRemark')}：{content.refundApproveRemark}</p>,
        ];
      }else if (action == '修改退款信息') {
        return [
          <i18n path="common.record.linkcOrder.editRefund" class="main-info" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
          </i18n>,
          <p class="secondary-info">{t('common.record.linkcOrder.refundMoney')}：{content.refundMoney}</p>,
          <p class="secondary-info">{t('common.record.linkcOrder.refundCause')}：{content.refundCause}</p>,
          createAttachmentDom(h, attachments),
        ];
      }else if (action == '撤销退款申请') {
        return [
          <i18n path="common.record.linkcOrder.cancelRefund" class="main-info" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
          </i18n>
        ];
      }

      return [
        <i18n path="common.record.linkcOrder.normal" tag="h5">
          <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
          <span place="action">{translateAction(action)}</span>
        </i18n>,
        content.fail ? <p class="secondary-info">{t('common.base.reason')}：{content.fail}</p> : '',
        createAttachmentDom(h, attachments),
      ];
    },
    renderUserName(userName, staffId, userId) {
      if (userId) {
        if (isOpenData && staffId)
          return (
            <strong class="user-card-triggle" v-user={userId}>
              {<open-data type="userName" openid={staffId}></open-data>}
            </strong>
          );
        return (
          <strong class="user-card-triggle" v-user={userId}>
            {userName}
          </strong>
        );
      }
      if (isOpenData && staffId)
        return (
          <strong>
            {<open-data type="userName" openid={staffId}></open-data>}
          </strong>
        );
      return <strong>{userName}</strong>;
    },
    // 物流信息
    async getLogisticsDetails() {
      this.orderLogisticsInfoLoading = true;
      try {
        const res = await getSimpleLogistics({ orderId: this.orderId });
        if (res.code === '200') {
          this.logisticsInfoList = res?.data || [];
        }
      } finally {
        this.orderLogisticsInfoLoading = false;
      }
    },
    // 关联服务
    async getMyService() {
      this.orderRelationLoading = true;
      try {
        const res = await myService({ orderId: this.orderId });
        if (res.code === '200') {
          this.myServiceList = res.data;
        }
      } finally {
        this.orderRelationLoading = false;
      }
    },
    // 商品信息
    async getOrderCommodity() {
      this.orderProductInfoLoading = true;
      try {
        const res = await orderWithCommodity({ orderId: this.orderId });
        if (res.code === '200') {
          this.orderCommodityList = res.data;
        }
      } finally {
        this.orderProductInfoLoading = false;
      }
    },
    /**
     * @description 创建备注
     */
    async createRemark(form) {
      try {
        this.recordLoading = true;
        let tenantId = useTenantId().value;
        let url = '';
        let orderInfo = this.dataInfo;
        if (form.receivers) {
          url = `?tenantId=${tenantId}&bizId=${orderInfo.orderId}&receivers=${form.receivers}&bizNo=${orderInfo.orderNum}`;
        }
        let params = {
          primaryId: orderInfo.orderId,
          orderNum: orderInfo.orderNum,
          attachments: form.attachments,
          showInOwn: form.showInOwn,
          content: {
            updateContent: form.content,
            updateType: 'ptRecord',
          },
        };
        params.url = url;
        let result = await addDynamic(params);

        if (result.success) {
          // 清除备注信息
          this.$refs.comment.reset();
          // 初始化备注
          await this.initializeRecord();
          // 滚动到顶部
          this.$nextTick(() => {
            this.$refs.timeline.scrollTop = 0;
          });
        } else {
          this.$platform.alert(result.message);
        }
      } catch (err) {
        console.warn(err);
      } finally {
        this.recordLoading = false;
      }
    },
    // 初始化信息动态
    async initializeRecord() {
      this.recordParams.pageNum = 1;
      await this.getOrderDynamic();
    },
    isAllServices() {
      if (!this.orderCommodityList?.length) return false;
      return this.orderCommodityList.every(v => v.originType === 2);
    },
    handleBalance() {
      if (this.balanceFields.length) {
        if (!this.$refs.BizFormDiaLogComponent) {
          setTimeout(() => {
            this.$refs.BizFormDiaLogComponent?.outsideShow();
          }, 1000)
        }

        this.$refs.BizFormDiaLogComponent?.outsideShow();
      } else {
        this.$confirm(this.$t('task.tip.settlementTip10'), this.$t('common.base.toast'), {
          confirmButtonText: this.$t('common.base.makeSure'),
          cancelButtonText: this.$t('common.base.cancel'),
          type: 'warning',
        })
          .then(() => {
            this.handleBalanceSubmit({});
          })
          .catch(() => {});
      }
    },
    handleBalanceSubmit(balanceFormData) {
      const packFormData = this.pack(balanceFormData)
      const params = {
        ...packFormData,
        ids: [this.dataInfo?.orderId],
      }
      console.log('params', params)
    },
    // 将数据打包成服务器可接收的数据
    pack(form) {
      let data = {}
      let attribute = {}
      let attachment = {}
      
      this.balanceFields.forEach(field => {
        if(field.formType == 'attachment') {
          attachment = form[field.fieldName];
        } else {
          attribute[field.fieldName] = form[field.fieldName];
        }
      })

      // 要对attachment校验一下 空对象foreach会报错
      Object.keys(attachment).length > 0 && attachment.forEach((item, index) => {
        data[`balanceAttachments[${index}]`] = item
      })
      
      data.balanceAttributes = attribute;
      return data;
    },
    // 获取结算自定义字段数据
    async fetchBalanceFieldInfo() {
      try {
        const result = await getTaskBalanceFieldInfo();
        // 是否启用工单自定义结算字段
        const openUserDefinedBalance = true;
        const balanceFields = openUserDefinedBalance ? result || [] : [];
        // 给结算自定义字段一个标识符，用于高级搜索的时候判断是否是结算自定义字段
        balanceFields.forEach(item => item.isBalanceField = true);
        this.balanceFields = balanceFields.filter(field => field.setting.isOpen);
      } catch (e) {
        console.error('fetchBalanceFieldInfo error', e);
      }
    },
  },
};
</script>
<style lang="scss">
@import '@src/modules/task/view/TaskDetailView.scss';
// @import '@src/assets/scss/common-detail.scss';
</style>
<style lang='scss' scoped>
.task-detail-container {
  .task-detail-header {
    padding: 12px;
    .top-box {
      display: flex;
      justify-content: space-between;
      .order_button_group{
        display: flex;
      }
    }
    .order_info {
      display: flex;
      margin-top: 12px;
      p {
        font-size: 12px;
        margin: 0 32px 0 0;

        span {
          color: #787878;
        }
      }
    }
  }
  .base-collapse {
    flex: 1;
  }
}
.detail-main-content-left ::v-deep .el-tabs__nav,
.detail-main-content-right ::v-deep .el-tabs__nav {
  white-space: normal;
  // background: #fff;
  padding-right: 44px;
  height: auto;
  font-size: 0;
  .el-tabs__item {
    padding: 0 !important;
    margin: 0 24px;
    height: 40px;
    line-height: 40px;
    max-width: 290px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    vertical-align: middle;
    &.is-active {
      border-bottom: 2px solid $color-primary-light-6;
    }
  }
  .el-tabs__active-bar {
    display: none;
  }
}
.task-detail-main-content-right {
  height: 100% !important;
}
.task-detail-main-content {
  min-height: 0 !important;
}
.task-detail-main-content .el-tabs__content .el-tab-pane {
  overflow: auto !important;
  padding-bottom: 24px;
}
.order_progress {
  height: 100%;
  justify-content: space-between;
  overflow-y: hidden;
  position: relative;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .base-timeline-wrap {
    overflow-y: scroll;
    padding: 0 0px 10px 0px;
    .base-timeline {
      padding-right: 15px;
      padding-top: 15px;
    }
  }
  .biz-comment-wrap {
    padding:0 20px;
  }
}

.card-info-container {
  padding: 16px;
  box-sizing: border-box;
} 
 // 审批中
.approving-img {
  width: 90px;
  position: absolute;
  top: 16px;
  right: 560px;
  z-index: 99;

  img {
    width: 100%;
  }
}
.detail {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
  .detail-layout {
    flex: 1;
    background-color: #fff;
    height: 100%;
    // overflow: auto;
    ::v-deep .el-tabs__content {
      height: calc(100% - 55px);
      padding-bottom: 24px;
    }
    ::v-deep .el-tab-pane {
      height: 100%;
    }
  }
}
.layoutDialog {
  position: absolute;
  right: 0;
  width: fit-content;
  height: 39px;
  align-items: normal;
  background: #fafafa;
  &::after {
    border: none;
  }
}
.layoutDialog2 {
  position: absolute;
}
.detail_h {
  // TODO 这里多列高度先这样写
  height: 88%;
}
.progress_column {
}
</style>
